
package com.kevin.session.defaults;

import java.sql.Connection;
import java.sql.SQLException;

import com.kevin.datasource.Environment;
import com.kevin.enums.transaction.TransactionIsolationLevel;
import com.kevin.exceptions.ExceptionFactory;
import com.kevin.executors.Executor;
import com.kevin.session.Configuration;
import com.kevin.session.SqlSession;
import com.kevin.session.SqlSessionFactory;
import com.kevin.transaction.Transaction;
import com.kevin.transaction.TransactionFactory;



public class DefaultSqlSessionFactory implements SqlSessionFactory {

  private final Configuration configuration;

  public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
  }

  @Override
  public SqlSession openSession(boolean autoCommit) {
    return openSessionFromDataSource(null,null, autoCommit);
  }

  @Override
  public SqlSession openSession() {
    return openSessionFromDataSource(null,null, false);
  }

  @Override
  public SqlSession openSession(String tableName) {
    return openSessionFromDataSource(tableName,null, false);
  }
  
  @Override
  public SqlSession openSession(TransactionIsolationLevel level) {
    return openSessionFromDataSource(null,level, false);
  }

  @Override
  public SqlSession openSession(Connection connection) {
    return openSessionFromConnection(null,connection);
  }

  @Override
  public SqlSession openSession(String tableName, boolean autoCommit) {
  	return openSessionFromDataSource(tableName,null, autoCommit);
  }

  @Override
  public SqlSession openSession(String tableName, Connection connection) {
	  return openSessionFromConnection(tableName,connection);
  }

  @Override
  public SqlSession openSession(String tableName, TransactionIsolationLevel level) {
	  return openSessionFromDataSource(tableName,level, false);
  }
  
  
  @Override
  public Configuration getConfiguration() {
    return configuration;
  }

  private SqlSession openSessionFromDataSource(String tableName,TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx);
      return new DefaultSqlSession(tableName,configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.Exception("Error opening session.  Cause: " + e, e);
    } finally {
      //ErrorContext.instance().reset();
    }
  }

  private SqlSession openSessionFromConnection(String tableName,Connection connection) {
    try {
      boolean autoCommit;
      try {
        autoCommit = connection.getAutoCommit();
      } catch (SQLException e) {
        // Failover to true, as most poor drivers
        // or databases won't support transactions
        autoCommit = true;
      }      
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      final Transaction tx = transactionFactory.newTransaction(connection);
      final Executor executor = configuration.newExecutor(tx);
      return new DefaultSqlSession(tableName,configuration, executor, autoCommit);
    } catch (Exception e) {
      throw ExceptionFactory.Exception("Error opening session.  Cause: " + e, e);
    } finally {
      //ErrorContext.instance().reset();
    }
  }

  private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
//    if (environment == null || environment.getTransactionFactory() == null) {
//      return new ManagedTransactionFactory();
//    }
    return environment.getTransactionFactory();
  }

  private void closeTransaction(Transaction tx) {
    if (tx != null) {
      try {
        tx.close();
      } catch (SQLException ignore) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }



}
